<template>
  <div>
    <i class="el-icon-chat-dot-square" @click="click"/>
    <el-dialog
      title="问答界面"
      :visible.sync="showDialog"
      @close='cancelFields'
      width="550px"
      class="my-dialog-name"
    >
      <span slot="title" class="Title">
        <img :src="titlePng" alt="" >
        <span>咨询助手</span>
      </span>
      <JwChat 
        :taleList="list" 
        @enter="bindEnter" 
        @clickTalk="talkEvent" 
        v-model="inputMsg"
        :toolConfig="tool" 
        :quickList="quickList"
        scrollType ='scroll'
      >
        <!-- <template slot="tools">
          <div style="width:20rem;text-align:right;" @click="toolEvent('自定义')">
            <b slot="tools">插槽</b>
            <JwChat-icon type="icon-lishi" title="自定义"/>
          </div>
        </template> -->
      </JwChat>
    </el-dialog>
  </div>
</template>
<script>
import {robotChat,chatHistory,getPageAll} from "@/api/infra/consult";
import { getUserProfile } from "@/api/system/user";
import titlePng from '@/assets/images/ic_kefu.png'
import kefuPng from '@/assets/images/pic_kefu.png'
export default {
  name: 'Consult',
  data() {
    return {
      kefuPng,
      titlePng,
      userInfo:{},//用户信息
      showDialog: false, //显示新建/编辑界面
      inputMsg: '',
      list: [],
      tool: {
        callback: this.toolEvent
      },
      quickList:[]  //模糊匹配问答标题
      // quickList: [
      //   {text: '这里是jwchat，您想了解什么问题。'},
      //   {text: 'jwchat是最好的聊天组件'},
      //   {text: '谁将烟焚散，散了纵横的牵绊；听弦断，断那三千痴缠。'},
      //   {text: '长夏逝去。山野间的初秋悄然涉足。'},
      //   {text: '江南风骨，天水成碧，天教心愿与身违。'},
      //   {text: '总在不经意的年生。回首彼岸。纵然发现光景绵长。'},
      //   {text: '外面的烟花奋力的燃着，屋里的人激情的说着情话'},
      //   {text: '假如你是云，我就是雨，一生相伴，风风雨雨；'},
      //   {text: '即使泪水在眼中打转，我依旧可以笑的很美，这是你学不来的坚强。'},
      //   {text: ' 因为不知来生来世会不会遇到你，所以今生今世我会加倍爱你。'},
      // ] 
    }
  },
  mounted() {
    getUserProfile().then(response => {
      this.userInfo = {
        avatar:response.data.avatar,
        id:response.data.id,
        nickname:response.data.nickname,
        username:response.data.username
      }
    })

    // const img = 'https://www.baidu.com/img/flexible/logo/pc/result.png'
    // const list = [
    //     {
    //       "date": "2020/04/25 21:19:07",
    //       "text": { "text": "您好，请问有什么可以帮您？" },
    //       "mine": false,
    //       "name": "留恋人间不羡仙",
    //       "img": "/image/one.jpeg"
    //     },
    //     {
    //       "date": "2021/03/02 13:14:21",
    //       "mine": false,
    //       "name": "留恋人间不羡仙",
    //       "img": "/image/one.jpeg",
    //       "text": {
    //         system: {
    //           title: '在接入人工前，智能助手将为您首次应答。',
    //           subtitle: '猜您想问:',
    //           content: [
    //             {
    //               id: `system1`,
    //               text: '组件如何使用'
    //             },
    //             {
    //               id: `system2`,
    //               text: '组件参数在哪里查看'
    //             },
    //             {
    //               id: 'system',
    //               text: '我可不可把组件用在商业'
    //             }
    //           ]
    //         }
    //       }
    //     }
    //   ]
    // this.list = list
    
  },
  methods: {
    //时间戳转日期时间
    getDateTime(time) {
      if (!time) return ''
      let date = new Date(time)
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      let hour = date.getHours()
      let minute = date.getMinutes()
      let second = date.getSeconds()
      return `${year}-${month<10?'0':''}${month}-${day<10?'0':''}${day} ${hour<10?'0':''}${hour}:${minute<10?'0':''}${minute}:${second<10?'0':''}${second}`
    },
    click() { //问答弹框
      let params = {
        issueTitle:'',
        id:null
      }
      getPageAll(params).then((res) => {
        if (res.code === 0) {
          res.data.map((item,index)=>{
            this.quickList.push(
              {
                text:item.issueTitle,
              }
            )
          })
          
        }
      }).catch((e) => {console.log(e);});
      this.showDialog =true

      //问答历史数据
      let params1 = {
        chatContent:'',
        fromUserId:this.userInfo.id,
        issueTitleId:'0',
        toType:0,
        time:'',
        toTypeId:0,
      }
      //自动问答数据获取
      chatHistory(params1).then((res) => {
        if (res.code === 0) {
          this.list = []
          res.data.map((item,index)=>{
            let tempContent = JSON.parse(item.chatContent)
            if(tempContent.relevanceConsult?.length>0){
              let connectQ = []
              tempContent.relevanceConsult.map((i,num)=>{
                connectQ.push({
                  id:i.id,
                  text:i.issueTitle
                })
              })
              this.list.push( {
                "date": this.getDateTime(item.createTime),
                "text": { 
                  system:{
                    // title:tempContent.chatAnswer?tempContent.chatAnswer:tempContent.chatIssueTitleList[0].answer,
                    title:tempContent.chatAnswer,
                    subtitle:'猜您还想问:',
                    content: connectQ
                  }
                },
                "mine": item.fromUserId === 0?false:true,
                "name": item.fromUserId === 0?'专属客服':this.userInfo.nickname,
                "img": item.fromUserId === 0?kefuPng:this.userInfo.avatar
              },)
            }else{
              this.list.push( {
                "date": this.getDateTime(item.createTime),
                "text": { "text": tempContent.chatAnswer?tempContent.chatAnswer:tempContent.chatIssueTitleList[0].answer },
                "mine": item.fromUserId === 0?false:true,
                "name": item.fromUserId === 0?'专属客服':this.userInfo.nickname,
                "img": item.fromUserId === 0?kefuPng:this.userInfo.avatar
              },)
            }
          })
          let lastAnswer =res.data.length>0 && JSON.parse(res.data[res.data.length-1].chatContent)?.chatAnswer
          if(res.data.length>0 && lastAnswer === '您好，请问有什么可以帮您？'){
            this.list.splice(this.list.length-1)
          }
          let params2 = {
            chatContent:'123',
            fromUserId:this.userInfo.id,
            issueTitleId:'0',
            toType:-1,
            time:'',
            toTypeId:0,
            historyId:res.data.length>0 && lastAnswer === '您好，请问有什么可以帮您？'?res.data[res.data.length-1].id:''
          }
          //自动问答数据获取
          robotChat(params2).then((res) => {
            if (res.code === 0) {
              let chatAnswer = JSON.parse(res.data.chatContent).chatAnswer
              this.list.push( {
                "date": this.getDateTime(res.data.createTime),
                "text": { "text": chatAnswer },
                "mine": false,
                "name": '专属客服',
                "img": kefuPng
              },)
            }
          }).catch((e)=>{console.log(e)})
        }
      }).catch((e)=>{console.log(e)})
    },
    cancelFields () {
      this.showDialog = false
      // this.$refs["basicForm"].clearValidate()
    },

    bindEnter (e) {
      const msg = this.inputMsg
      if (!msg) return;
      const msgObj = {
        "date": this.getDateTime(Date.now()),
        "text": { "text": msg },
        "mine": true,
        "name": this.userInfo.nickname,
        "img": this.userInfo.avatar
      }
      this.list.push(msgObj)
      let params = {
        chatContent:msg,
        fromUserId:this.userInfo.id,
        issueTitleId:'',
        toType:0,
        toTypeId:0,
        time:Date.now(),
        historyId:''
      }
      //自动问答数据获取
      robotChat(params).then((res) => {
        if (res.code === 0) {
          let chatContent = JSON.parse(res.data.chatContent)
          // chatContent = chatContent.chatAnswer?chatContent.chatAnswer:chatContent.chatIssueTitleList[0].answer
          if(chatContent.relevanceConsult?.length>0){
            let connectQ = []
            chatContent.relevanceConsult.map((i,num)=>{
              connectQ.push({
                id:i.id,
                text:i.issueTitle
              })
            })
            this.list.push({
              "date": this.getDateTime(res.data.createTime),
              "text": { 
                system:{
                  // title:tempContent.chatAnswer?tempContent.chatAnswer:tempContent.chatIssueTitleList[0].answer,
                  title:chatContent.chatAnswer,
                  subtitle:'猜您还想问:',
                  content: connectQ
                }
              },
              "mine": false,
              "name": '专属客服',
              "img": kefuPng
            })
          }else{
            this.list.push({
              "date": this.getDateTime(res.data.createTime),
              // "text": { "text": tempContent.chatAnswer?tempContent.chatAnswer:tempContent.chatIssueTitleList[0].answer },
              "text": { "text": chatContent.chatAnswer},
              "mine": false,
              "name": '专属客服',
              "img": kefuPng
            })
          }
        }
      }).catch((e)=>{console.log(e)})
    },
    toolEvent (type, obj) {
      console.log('tools', type, obj)
    },
    //关联问题点击事件
    talkEvent (play) {

      this.list.push({
        "date": this.getDateTime(Date.now()),
        "text": { "text": play.data.text},
        "mine": true,
        "name": this.userInfo.nickname,
        "img": this.userInfo.avatar
      })
      let params = {
        chatContent:play.data.text,
        fromUserId:this.userInfo.id,
        issueTitleId:'',
        toType:0,
        toTypeId:0,
        time:Date.now(),
        historyId:''
      }
      //自动问答数据获取
      robotChat(params).then((res) => {
        if (res.code === 0) {
          
          let chatContent = JSON.parse(res.data.chatContent)
          // chatContent = chatContent.chatAnswer?chatContent.chatAnswer:chatContent.chatIssueTitleList[0].answer
          if(chatContent.relevanceConsult?.length>0){
            let connectQ = []
            chatContent.relevanceConsult.map((i,num)=>{
              connectQ.push({
                id:i.id,
                text:i.issueTitle
              })
            })
            this.list.push({
              "date": this.getDateTime(res.data.createTime),
              "text": { 
                system:{
                  // title:tempContent.chatAnswer?tempContent.chatAnswer:tempContent.chatIssueTitleList[0].answer,
                  title:chatContent.chatAnswer,
                  subtitle:'猜您还想问:',
                  content: connectQ
                }
              },
              "mine": false,
              "name": '专属客服',
              "img": kefuPng
            })
          }else{
            this.list.push({
              "date": this.getDateTime(res.data.createTime),
              // "text": { "text": tempContent.chatAnswer?tempContent.chatAnswer:tempContent.chatIssueTitleList[0].answer },
              "text": { "text": chatContent.chatAnswer},
              "mine": false,
              "name": '专属客服',
              "img": kefuPng
            })
          }
        }
      }).catch((e)=>{console.log(e)})
      
    },
  }
}
</script>

<style lang="scss" scoped>
  i{
    cursor: pointer;
    font-size: 18px;
    font-weight: 900;
  }
 
</style>

<style lang="scss">
 .quickListBox .quickItem[data-v-33df78c4] {
    align-items: center;
    padding: 0;
    border-bottom: 1px solid #f7f7f7;
    height: 32px;
  }
  .my-dialog-name {
    .Title {
      display: flex;
      align-items: center;
      color: white;
      font-size: 16px;
    }
    .el-dialog__body{
      padding: 0;
      padding-top: 10px;
    }
    .el-dialog__header{
      background:#1C81F8 !important;
      padding: 0 0 0 10px;
    }
    .el-dialog__headerbtn {
      top: 0;
    }
    .el-dialog__headerbtn .el-dialog__close{
      color: white;
    }
    .wrapper .web__main[data-v-8592dc42]{
      padding: 0px;
    }
    .wrapper .web__main .web__main-user img[data-v-8592dc42]{
      width: 32px;
      height: 32px;
    }
  }

</style>


